package com.example.gokuplayalong.bases.network.updown;


import static com.mob.tools.utils.DH.SyncMtd.getPackageName;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;

import androidx.core.content.FileProvider;

import com.example.gokuplayalong.MainActivity;
import com.example.gokuplayalong.bases.exception.ExceptionUtils;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class DownLoad {
    static DownLoad INSTANCE = null;

    UploadDownInterface uploadDownInterface;

    public static DownLoad getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new DownLoad();
        }
        return INSTANCE;
    }


    public void downloadFile(String fileUrl, String localFileUrl, UploadDownInterface uploadDownInterface) {
        try {
            OkHttpClient okHttpClient = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(fileUrl)
                    .build();
            okHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    uploadDownInterface.downFailed();
                }

                @Override
                public void onResponse(Call call, Response response) {
                    try {

                        byte[] bytes = response.body().bytes();

                        if (bytes.length > 0) {
                            File file = new File(localFileUrl);
                            if (file.exists()) file.delete();
                            OutputStream os = Files.newOutputStream(Paths.get(localFileUrl));
                            os.write(bytes);
                            os.close();
                        }
                        uploadDownInterface.downSuccess();


                    } catch (Throwable e) {
                        ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                    }

                }
            });
        } catch (Throwable e) {
            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
        }
    }

    public static String getVersionName() {
        String currentVersionName = "1.0.0";
        try {
            PackageInfo packageInfo = packageInfo = MainActivity.getInstance().getPackageManager()
                    .getPackageInfo(getPackageName(), 0);

            //获取APP版本versionName
            currentVersionName = packageInfo.versionName;
        } catch (Throwable e) {
            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
        }

        return currentVersionName;
    }

    public static String getApkVersionName(Context context, String apkPath) {
        PackageManager pm = context.getPackageManager();
        PackageInfo info = pm.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);
        if (info != null) {
            ApplicationInfo appInfo = info.applicationInfo;
            String packageName = appInfo.packageName;  //得到安装包名称
            String version = info.versionName;//获取安装包的版本号
            return version;
        }
        return null;

    }

    public static void installApk(Context context, String filename) {
        File apkfile = new File(filename);
        if (!apkfile.exists()) {
            return;
        }

        Intent intent = new Intent(Intent.ACTION_VIEW);


        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //兼容android7.0以上版本
        Uri uri = Uri.fromFile(apkfile);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //通过FileProvider创建一个content类型的Uri
            uri = FileProvider.getUriForFile(context, "com.example.gokuplayalong.fileprovider", apkfile);
            // 给目标应用一个临时授权
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        context.startActivity(intent);

    }

}
